import * as qiniu from 'qiniu-js';
import { QINIU_DOMAIN, UPTOKEN_HOST } from './setting';
import {
  notification,
  message,
} from 'antd';
import request from './request';
import G from './g';
let uptoken = '';
function getUptoken(){
    request(`${UPTOKEN_HOST}/api/fileUpload/findToken`).then((res)=>{
        //console.log(res);
        uptoken = res.uptoken;
    });
}
getUptoken();


export default function QiniuUploader(parms = {}){
  const { file, success, next, error } = parms;
  if(typeof file == 'undefined'){
    message.error('上传文件不能为空');
    typeof error == 'function' && error('上传文件不能为空');
    return;
  }
  else if(uptoken === ''){
    message.error('uptoken不能为空，请检查uptoken请求');
    return ;
  }

  const fileName = G.uuid(16) + '.' + file.name.split('.')[1];

  var putExtra = {
    //fname: file.name,
    fname: fileName,
    params: {},
    mimeType: [] || null,
    ...parms.putExtra
  };
  const config = {
    useCdnDomain: true,
    region: qiniu.region.z0
  };
  var observable = qiniu.upload(file, fileName, uptoken, putExtra, config);
  var observer = {
    next(res){
      console.log(res);
      typeof next == 'function' && next(res);
    },
    error(err){
      console.log(err);
        if(err.code == 400 || err.code == 401){
            notification.error({
                message: '上传失败，请重试'
            })
            getUptoken();
        }else{
            notification.error({
                message: err.message,
            });
        }

      typeof error == 'function' && error(err);
    },
    complete : (res)=>{
      console.log(res);
      typeof success == 'function' && success(`${QINIU_DOMAIN}${res.key}`);
    }
  };

  var subscription = observable.subscribe(observer); // 这样传参形式也可以
}


